/**
 * Created by 小敏哥 on 2017/3/23.
 */
import React, {Component} from 'react';
import ReactCSSTransitionGroup from "react-addons-css-transition-group"
import style from './dropDownBox.scss';
import 'style/reactAnimation/bottomToUp.scss';


class DropDownBox extends Component {
    constructor(props) {
        super(props);
        this.state = {
            selected: 0,
            show: false
        };
        //此处封装静态方法，供父控件调用
        DropDownBox.showComponent = this.showComponent.bind(this);
    }


    //静态方法，方便父控件调用
    showComponent(showStatus) {
        this.setState({
            show: showStatus
        })
    }

    //设置选中项并通知父控件
    setSelectItemAndCallBack(index) {
        this.setState({
            selected: index
        });
        DropDownBox.showComponent(false);
        this.props.onChange(index)
    }


    componentDidUpdate(prevProps,prevState){
        //设置默认项
        if(prevProps.data!==this.props.data&&this.props.selectedIndex&&this.props.selectedIndex!=this.state.selected){
            this.setSelectItemAndCallBack(this.props.selectedIndex);
        }
    }


    render() {
        return <div>
            {this.state.show ?<div className={style.mask} onClick={()=>{DropDownBox.showComponent(false)}}></div>:''}
            <ReactCSSTransitionGroup className={style.dropDownBox} transitionName="up-and-down" component="div"
                                     transitionAppear={true} transitionAppearTimeout={500}
                                     transitionEnterTimeout={500} transitionLeaveTimeout={500}>
                {this.state.show ? <div key="car-number-picker">
                        {this.props.data.map(i => (
                            <div className={style.dropDownItem} key={i.value}
                                 onClick={() => this.setSelectItemAndCallBack(i.value)}>{i.label}</div>
                        ))}
                    </div> : ''}

            </ReactCSSTransitionGroup>
        </div>
    }
}

export default DropDownBox